import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {PageSubject} from '../../../../util/page-subject';
import {TreeUtil} from '../../../../util/tree-util';
import {MsgResult} from '../../../../models/msg-result';
import {ActivatedRoute, Router} from '@angular/router';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {ResponseUtil} from '../../../../util/response-util';
import {Path} from '../../../../portal/admin/admin-breadcrumb/breadcrumb';
import {OneDialogService} from '../../../../widgets/one-dialog/one-dialog.service';
import {MsgConstants} from '../../../../constants/constants';
import {SiteManageService} from '../site-manage.service';
import { SiteRange } from '../site-range';
import {MapUtil} from '../../../../util/map-util';
import {DataDictionaryService} from '../../../../services/dataDictionary.service';

declare var moment;
declare var BMap;

@Component({
  selector: 'app-mobile-device-add',
  templateUrl: './site-range-add.component.html',
  styleUrls: ['./site-range-add.component.css']
})
export class SiteRangeAddComponent implements OnInit {
  @ViewChild('addressMap') addressMap: ElementRef;
  // 声明实例
  siteRange: SiteRange;
  id: string;
  siteRangeForm: FormGroup;

  siteId = '';


  modeTypeArr: Array<any> = [
    {display: '定点', value: '0'},
    {display: '巡航', value: '1'}
  ];

  // 所有行政区划数据
  regionsArr: Array<any> = [];
  regionsNameArr: Array<any> = [];

  // 历史地址信息
  historyAddrArr: Array<any> = [];

  /**
   * 校验字段
   */
  formErrors = {
    'rangeName': '',
    'regionCode': '',
    'startDate': '',
    'endDate': '',
    'address': '',
    'remark': '',
    'longitude': '',
    'latitude': ''
  };

  /**
   * 校验提示信息
   */
  validationMessages = {
    'siteCode': {
      'required': '不能为空',
      'maxlength': '长度不能超过50',
    },
    'rangeName': {
      'required': '不能为空',
      'maxlength': '长度不能超过20',
    },
    'regionCode': {
      'required': '不能为空'
    },
    'startDate': {
      'required': '不能为空'
    },
    'endDate': {
      'required': '不能为空'
    },
    'address': {
      'required': '不能为空',
      'maxlength': '长度不能超过100'
    },
    'remark': {
      'maxlength': '长度不能超过200'
    },
    'latitude': {
      'pattern': '格式不正确'
    },
    'longitude': {
      'pattern': '格式不正确'
    }
  };

  siteCode = '';

  airTypeCode = 'ZDKQLX';
  airTypeArr: Array<any> = [];

  map: any;
  point: any;
  marker: any;
  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private fb: FormBuilder,
    private responseUtil: ResponseUtil,
    private treeUtil: TreeUtil,
    private pageSubject: PageSubject,
    private dialogService: OneDialogService,
    private siteManageService: SiteManageService,
    private dicService: DataDictionaryService,
    private mapUtil: MapUtil
  ) {
    this.initObject();
  }

  ngOnInit() {
    this.pushPage();
    this.loadMapScript();
    this.initData();
    this.getRegionsTree();
    this.getHistory();
    this.getDicPolluteType();
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    const path = new Path('设备接入管理', '');
    this.pageSubject.pushPage('移动设备管理', '新增', path);
  }
  initData() {
    this.siteCode = this.route.snapshot.params['siteCode'];
    this.siteId = this.route.snapshot.params['addSiteId'];
  }
  loadMapScript() {
    this.mapUtil.loadMapScript(() => this.initMap());
  }

  initMap () {
    this.map = new BMap.Map('addressMap', {enableMapClick: false, minZoom: 5, maxZoom: 18});
    this.point = new BMap.Point(113.658221, 34.780377);
    this.map.centerAndZoom(this.point, 12);
    // 地图样式
    const mapStyle = [
      {
        'featureType': 'land',
        'elementType': 'geometry',
        'stylers': {
          'color': '#e7f7fc'
        }
      },
      {
        'featureType': 'water',
        'elementType': 'all',
        'stylers': {
          'color': '#96b5d6'
        }
      },
      {
        'featureType': 'green',
        'elementType': 'all',
        'stylers': {
          'color': '#b0d3dd'
        }
      },
      {
        'featureType': 'highway',
        'elementType': 'geometry.stroke',
        'stylers': {
          'color': '#d1c6a6'
        }
      },
      {
        'featureType': 'highway',
        'elementType': 'geometry.fill',
        'stylers': {
          'color': '#e6d9ab'
        }
      },
      {
        'featureType': 'arterial',
        'elementType': 'geometry.fill',
        'stylers': {
          'color': '#eeeeee'
        }
      },
      {
        'featureType': 'arterial',
        'elementType': 'geometry.stroke',
        'stylers': {
          'color': '#cccccc'
        }
      },
      {
        'featureType': 'local',
        'elementType': 'geometry.fill',
        'stylers': {
          'color': '#eeeeee'
        }
      },
      {
        'featureType': 'water',
        'elementType': 'geometry.fill',
        'stylers': {
          'color': '#b6c6de'
        }
      },
      {
        'featureType': 'subway',
        'elementType': 'all',
        'stylers': {
          'visibility': 'off'
        }
      },
      {
        'featureType': 'green',
        'elementType': 'geometry.fill',
        'stylers': {
          'color': '#cddbd2'
        }
      },
      {
        'featureType': 'land',
        'elementType': 'all',
        'stylers': {
          'color': '#edf1f5'
        }
      },
      {
        'featureType': 'administrative',
        'elementType': 'geometry',
        'stylers': {
          'color': '#a7c8ec'
        }
      },
      {
        'featureType': 'railway',
        'elementType': 'all',
        'stylers': {
          'visibility': 'off'
        }
      }
    ]; // 白底
    this.map.setMapStyle({styleJson: mapStyle});
    this.mapUtil.loadMapLib('http://api.map.baidu.com/library/InfoBox/1.2/src/InfoBox_min.js');
    this.mapLabel();
  }
  /*
 * 站点标注
 */
  mapLabel() {
    const point = this.point;
    const myIcon = new BMap.Icon('assets/v1/css/map/imgs/site-range-real.svg', new BMap.Size(26, 28));
    myIcon.setImageSize(new BMap.Size(26, 28));
    myIcon.setAnchor(new BMap.Size(13, 28));
    this.marker = new BMap.Marker(point, {
      icon: myIcon
    });
    this.map.addOverlay(this.marker);
    this.map.centerAndZoom(this.point, this.map.getZoom());
    this.map.enableScrollWheelZoom();
    this.marker.enableDragging();
    this.marker.addEventListener('dragend', () => {   // 标注的拖拽事件
      this.markerDragFunction(this.marker);
    });
  }
  markerDragFunction = (myMarker) => {
    const markerPoint = myMarker.getPosition();
    this.siteRangeForm.patchValue({longitude: markerPoint.lng + ',' + markerPoint.lat});
  };
  modeChange = (e) => {
    if (!e && this.siteRangeForm.value.modeType === '0') {
      const display = this.addressMap.nativeElement.style.display;
      if (display === 'none') {
        setTimeout(() => {
          this.map.centerAndZoom(this.point, this.map.getZoom());
        }, 100)
      }
    }
  };
  /**
   * 构造表单
   */
  buildForm(): void {
    this.siteRangeForm = this.fb.group({
      'id': [this.siteRange.id],
      'rangeName': [this.siteRange.rangeName, [
        Validators.required,
        Validators.maxLength(20),
      ]],
      'rangeCode': [this.siteRange.rangeCode],
      'regionCode': [this.siteRange.regionCode],
      // 'siteCode': [this.siteRange.siteCode, [
      //   Validators.required,
      //   Validators.maxLength(50),
      // ]],
      'startDate': [this.siteRange.startDate, [
        Validators.required
      ]],
      'endDate': [this.siteRange.endDate, [
        Validators.required
      ]],
      'modeType': [this.siteRange.modeType || '', [
        Validators.required
      ]],
      'airType': [this.siteRange.airType || '', [
        Validators.required
      ]],
      'address': [this.siteRange.address || '', [
        Validators.required,
        Validators.maxLength(100)
      ]],
      'longitude': [this.siteRange.longitude, [
        // Validators.pattern(/^[0-9.]{6,16}$/)
      ]],
      'latitude': [this.siteRange.latitude, [
        // Validators.pattern(/^[0-9.]{6,16}$/)
        ]],
      'remark': [this.siteRange.remark],
      'isUse': [this.siteRange.isUse || '0', [
        Validators.required,
        Validators.maxLength(1)
      ]]
    });

    this.siteRangeForm.valueChanges.subscribe(
      data => this.onValueChanged(data)
    );
    this.onValueChanged();
  }
  /**
   * 值变化监听
   * @param data
   */
  onValueChanged(data?: any) {
    if (!this.siteRangeForm) {
      return;
    }
    const form = this.siteRangeForm;
    for (const field in this.formErrors) {
      if (this.formErrors.hasOwnProperty(field)) {
        this.formErrors[field] = '';
        const control = form.get(field);
        if (control && control.dirty && !control.valid) {
          const messages = this.validationMessages[field];
          for (const key in control.errors) {
            if (control.errors.hasOwnProperty(key)) {
              this.formErrors[field] += messages[key] + ' ';
            }
          }
        }
      }
    }
  }



  /**
   * 添加站点类型
   */
  onSubmit() {
    this.siteRange = this.siteRangeForm.value;
    const regionAr = this.siteRange.regionCode;
    this.siteRange.siteCode = this.siteCode;
    this.siteRange.regionCode = regionAr[regionAr.length - 1];
    this.siteRange.startDate = moment(this.siteRange.startDate).format('YYYY-MM-DD HH:mm:ss');
    this.siteRange.endDate = moment(this.siteRange.endDate).format('YYYY-MM-DD HH:mm:ss');
    if (this.siteRange.modeType === '1') {
      this.siteRange.latitude = null;
      this.siteRange.longitude = null;
    } else {
      if (this.siteRange.longitude) {
        const dataArr = this.siteRange.longitude.split(',');
        this.siteRange.longitude = dataArr[0];
        this.siteRange.latitude = dataArr[1];
      }
    }
    this.siteManageService.postSiteRange(this.siteRange).subscribe(
      result => this.responseUtil.success(result, this.processResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   *  获取添加信息
   * @param result
   */
  private processResult = (result: MsgResult) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      this.dialogService.successWithCancelBtn('添加成功，是否继续添加？', () => this.initObject(), () => this.cancelMobileDevAdd());
    }
    if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };
  /**
   * 取消添加
   */
  cancelMobileDevAdd() {
    this.router.navigate(['..'], {relativeTo: this.route});
  }

  /**
   * 实例化对象
   */
  private initObject() {
    this.siteRange = new SiteRange();
    this.buildForm();
  }
  /**
   * 获取行政区划树
   */
  getRegionsTree () {
    let regionCode = this.route.snapshot.params['regionCode'];
    regionCode = regionCode? regionCode: '0';
    this.siteManageService.getRetrieveRegionsTree(regionCode).subscribe(
      result => this.responseUtil.success(result,  () => {
        if (result && result.code === MsgConstants.MSG_CODE_OK && result.data) {
          if (regionCode) {
            this.regionsArr = [result.data];
          } else {
            this.regionsArr = result.data.children;
          }
        }
        if (result && result.code !== MsgConstants.MSG_CODE_OK) {
          this.dialogService.info(result.message);
        }
      }),
      error => this.responseUtil.error(error)
    );
  }
  regionChange = (value) => {
    this.regionsNameArr = [];
    if (value.length > 0) {
      value.forEach(val => this.regionsNameArr.push(val.name))
    }
  };

  /**
   * 绑定设备
   */
  assignDevice() {
    this.siteRange = this.siteRangeForm.value;
    const regionAr = this.siteRange.regionCode;
    this.siteRange.siteCode = this.siteCode;
    this.siteRange.regionCode = regionAr[regionAr.length - 1];
    this.siteRange.startDate = moment(this.siteRange.startDate).format('YYYY-MM-DD HH:mm:ss');
    this.siteRange.endDate = moment(this.siteRange.endDate).format('YYYY-MM-DD HH:mm:ss');
    if (this.siteRange.modeType === '1') {
      this.siteRange.latitude = null;
      this.siteRange.longitude = null;
    } else {
      if (this.siteRange.longitude) {
        const dataArr = this.siteRange.longitude.split(',');
        this.siteRange.longitude = dataArr[0];
        this.siteRange.latitude = dataArr[1];
      }
    }
    this.siteManageService.postSiteRange(this.siteRange).subscribe(
      result => this.responseUtil.success(result, this.processAssignDeviceResult),
      message => this.responseUtil.error(message)
    );
  }
  /**
   *  处理保存结果
   * @param result
   */
  private processAssignDeviceResult = (result: MsgResult) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      // this.router.navigate(['../assign',{addSiteCode:result.data.siteCode}],{relativeTo :this.route});
      this.router.navigate(['../assign', {addSiteId: this.siteCode}], {relativeTo: this.route});
    }
    if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };

  /**
   * 获取历史位置信息
   */
  getHistory() {
    this.siteManageService.getHistoryAddr(this.siteCode).subscribe(
      result => this.responseUtil.success(result, () => {
        if (result && result.code === MsgConstants.MSG_CODE_OK) {
          if (result.data && result.data.length > 0) {
            this.historyAddrArr = result.data
          }
        }
        if (result && result.code !== MsgConstants.MSG_CODE_OK) {
          this.dialogService.info(result.message);
        }
      }),
      message => this.responseUtil.error(message)
    );
  }
  changeSearch(data?: any) {
    if (data) {
      this.siteRangeForm.patchValue({rangeName: data.rangeName, rangeCode: data.rangeCode, address: data.address,longitude: data.longitude + ','+  data.latitude});
      this.siteRangeForm.controls.address.disable();
      const point = new BMap.Point(data.longitude, data.latitude);
      this.point = point;
      this.marker.setPosition(point);
      this.marker.disableDragging();
      this.map.centerAndZoom(this.point, this.map.getZoom());
    }
    this.siteRange =  this.siteRangeForm.value;
    if (!data) {
      const rangeName = this.siteRange.rangeName;
      let historyData;
      this.historyAddrArr.every((val) => {
        if (val.rangeName === rangeName) {
          historyData = val;
          return false;
        } else {
          return true;
        }
      });
      if (historyData) {
        const point = new BMap.Point(historyData.longitude, historyData.latitude);
        this.point = point;
        this.marker.setPosition(point);
        this.marker.disableDragging();
        this.map.centerAndZoom(this.point, this.map.getZoom());
        this.siteRangeForm.controls.address.disable();
        this.siteRangeForm.patchValue({address: historyData.address,longitude: historyData.longitude + ','+  historyData.latitude});
      } else {
        this.siteRangeForm.controls.address.enable();
        this.marker.enableDragging();
        const myGeo = new BMap.Geocoder();
        // 将地址解析结果显示在地图上,并调整地图视野
        myGeo.getPoint(rangeName, (point) => {
          if (point) {
            this.marker.setPosition(point);
            this.map.centerAndZoom(point, this.map.getZoom());
            this.siteRangeForm.patchValue({longitude: point.lng + ',' + point.lat});
            const display = this.addressMap.nativeElement.style.display;
            if (display === 'none') {
              this.map.panBy(100, 100);
            }
            this.point = point;
          } else {
            this.map.centerAndZoom(this.point, this.map.getZoom());
          }
        }, this.regionsNameArr.join(','));
      }
    }

  };
  /**
   * 开始时间结束时间
   */
  startValueChange = () => {
    if (this.siteRangeForm.value.startDate > this.siteRangeForm.value.endDate) {
      this.siteRangeForm.value.endDate = null;
    }
  };
  endValueChange = () => {
    if (this.siteRangeForm.value.startDate > this.siteRangeForm.value.endDate) {
      this.siteRangeForm.value.startDate = null;
    }
  };
  disabledStartDate = (startValue) => {
    if (!startValue || !this.siteRangeForm.value.endDate) {
      return false;
    }
    return startValue.getTime() > this.siteRangeForm.value.endDate.getTime();
  };
  disabledEndDate = (endValue) => {
    if (!endValue || !this.siteRangeForm.value.startDate) {
      return false;
    }
    return endValue.getTime() < this.siteRangeForm.value.startDate.getTime();
  };

  /**
   * 获取数据字典中站点类型-大类
   */
  getDicPolluteType () {
    this.dicService.getChildDicByCode(this.airTypeCode).subscribe(
      result => this.responseUtil.success(result,  () => {
        if (result && result.code === MsgConstants.MSG_CODE_OK) {
          if (result.data.length > 0) {
            this.airTypeArr = result.data;
          }
        }
        if (result && result.code !== MsgConstants.MSG_CODE_OK) {
          this.dialogService.info(result.message);
        }
      }),
      error => this.responseUtil.error(error)
    );
  }
}
